package com.library.web.user;

import com.library.dao.UserDAO;
import com.library.model.User;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.WebServlet;

import java.io.IOException;
import java.util.List;

@WebServlet("/user")
public class UserServlet extends HttpServlet {

    private final UserDAO userDAO = new UserDAO();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String action = request.getParameter("action");

        if (action == null || "list".equals(action)) {
            String username = request.getParameter("username");
            String email = request.getParameter("email");
            String phone = request.getParameter("phone");
            String role = request.getParameter("role");

            List<User> users = userDAO.findUserByCondition(username, email, phone, role);
            request.setAttribute("users", users);
            request.getRequestDispatcher("user/user.jsp").forward(request, response);
        }  else if ("delete".equals(action)) {
            int id = Integer.parseInt(request.getParameter("id"));
            userDAO.delete(id);
            response.sendRedirect("user?action=list");
        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String action = request.getParameter("action");

        if ("add".equals(action)) {
            User user = new User();
            user.setUsername(request.getParameter("username"));
            user.setEmail(request.getParameter("email"));
            user.setPhone(request.getParameter("phone"));
            user.setPassword(request.getParameter("password"));
            user.setRole(request.getParameter("role"));

            userDAO.add(user);

            response.sendRedirect("users?action=list");
        } else if ("update".equals(action)) {
            try {
                User user = new User();
                user.setId(Integer.parseInt(request.getParameter("id")));

                user.setUsername(request.getParameter("username"));
                user.setEmail(request.getParameter("email"));
                user.setPhone(request.getParameter("phone"));
                user.setPassword(request.getParameter("password"));
                user.setRole(request.getParameter("role"));
                userDAO.update(user);

            } catch (Exception e) {
                e.printStackTrace();
            }
            response.sendRedirect("user?action=list");
        }
    }
}
